package com.glowdayz.glowmee;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PorterDuff;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.glowdayz.common.CDialog;
import com.glowdayz.common.XmlParser;
import com.glowdayz.model.AddItem;
import com.glowdayz.model.RegisterCMD;
import com.glowdayz.model.UserInfo;
import com.google.android.gcm.GCMRegistrar;

public class More extends Fragment implements OnItemClickListener, OnClickListener, OnCheckedChangeListener {
	
	ListView listMore = null;
	DataAdapter adapter = null;
	LinearLayout llHeader = null;
	
	EditText eMail = null, password = null;
	CheckBox autoLogin = null;
	TextView searchPw = null, autoLoginText = null;
	ImageView loginBt = null, joinBtn = null;
	String url = "", mail = null, nickName = null;
	
	ImageView backUserImg = null, frontUserImg = null;
	TextView userNickName = null, userInfo = null;
	Bitmap bm = null;
	boolean isImage = false;
	LinearLayout profileLayoutBt = null;
	ImageView editProfileBt = null;
	TextView picksCount = null, likesCount = null, reviewsCount = null;
	
	String facebook = null, partner = null, version = null;
	
	DrawerLayout dlDrawerIndex;
	
	String regId = "";
	
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        View nowView = inflater.inflate(R.layout.activity_more, container, false);
        
        dlDrawerIndex = (DrawerLayout) getActivity().findViewById(R.id.drawer_layout);
		dlDrawerIndex.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
		
		ImageView backBt = (ImageView) nowView.findViewById(R.id.backBt);
		ImageView okBt = (ImageView) nowView.findViewById(R.id.okBt);
		backBt.setVisibility(View.GONE);
		okBt.setVisibility(View.GONE);
		
		TextView textTitle = (TextView) nowView.findViewById(R.id.textTitle);
		textTitle.setText("더보기");
		
		listMore = (ListView) nowView.findViewById(R.id.listMore);
		LayoutInflater inflater2 = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		
		if (UserInfo.getInstance().getUSER_ID() > 0) {
			ImageView guestBt = (ImageView) getActivity().findViewById(R.id.guestBt);
			guestBt.setVisibility(View.GONE);
			
			llHeader = (LinearLayout) inflater2.inflate(R.layout.inc_more_header2, null);
			
			backUserImg = (ImageView) llHeader.findViewById(R.id.backUserImg);
			frontUserImg = (ImageView) llHeader.findViewById(R.id.frontUserImg);
			userNickName = (TextView) llHeader.findViewById(R.id.userNickName);
			userInfo = (TextView) llHeader.findViewById(R.id.userInfo);
			
			profileLayoutBt = (LinearLayout) llHeader.findViewById(R.id.profileLayoutBt);
			profileLayoutBt.setOnTouchListener(new OnTouchListener() {
				@Override
				public boolean onTouch(View v, MotionEvent arg1) {
					v.setBackgroundResource(android.R.drawable.list_selector_background);
					return false;
				}
			});
			profileLayoutBt.setOnClickListener(this);
			
			editProfileBt = (ImageView) llHeader.findViewById(R.id.editProfileBt);
			editProfileBt.setOnTouchListener(new OnTouchListener() {
	            @Override
	            public boolean onTouch(View v, MotionEvent event) {
	                switch (event.getAction()) {
	                    case MotionEvent.ACTION_DOWN: {
	                        ImageView view = (ImageView) v;
	                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
	                        view.invalidate();
	                        break;
	                    }
	                    case MotionEvent.ACTION_UP:
	                    case MotionEvent.ACTION_CANCEL: {
	                        ImageView view = (ImageView) v;
	                        view.getDrawable().clearColorFilter();
	                        view.invalidate();
	                        break;
	                    }
	                }
	                return false;
	            }
	        });
			editProfileBt.setOnClickListener(this);
			
			picksCount = (TextView) llHeader.findViewById(R.id.picksCount);
			likesCount = (TextView) llHeader.findViewById(R.id.likesCount);
			reviewsCount = (TextView) llHeader.findViewById(R.id.reviewsCount);
			
			(new ProfileWorker()).execute();
			
		} else {
			llHeader = (LinearLayout) inflater2.inflate(R.layout.inc_more_header1, null);
			
			eMail = (EditText) llHeader.findViewById(R.id.eMail);
			password = (EditText) llHeader.findViewById(R.id.password);
			
			autoLogin = (CheckBox) llHeader.findViewById(R.id.autoLogin);
			autoLogin.setOnCheckedChangeListener(this);
			
			searchPw = (TextView) llHeader.findViewById(R.id.searchPw);
			searchPw.setOnClickListener(this);
			
			autoLoginText = (TextView) llHeader.findViewById(R.id.autoLoginText);
			autoLoginText.setOnClickListener(this);
			
			loginBt = (ImageView) llHeader.findViewById(R.id.loginBt);
			loginBt.setOnTouchListener(new OnTouchListener() {
	            @Override
	            public boolean onTouch(View v, MotionEvent event) {
	                switch (event.getAction()) {
	                    case MotionEvent.ACTION_DOWN: {
	                        ImageView view = (ImageView) v;
	                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
	                        view.invalidate();
	                        break;
	                    }
	                    case MotionEvent.ACTION_UP:
	                    case MotionEvent.ACTION_CANCEL: {
	                        ImageView view = (ImageView) v;
	                        view.getDrawable().clearColorFilter();
	                        view.invalidate();
	                        break;
	                    }
	                }
	                return false;
	            }
	        });
			loginBt.setOnClickListener(this);
			
			joinBtn = (ImageView) llHeader.findViewById(R.id.joinBtn);
			joinBtn.setOnTouchListener(new OnTouchListener() {
	            @Override
	            public boolean onTouch(View v, MotionEvent event) {
	                switch (event.getAction()) {
	                    case MotionEvent.ACTION_DOWN: {
	                        ImageView view = (ImageView) v;
	                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
	                        view.invalidate();
	                        break;
	                    }
	                    case MotionEvent.ACTION_UP:
	                    case MotionEvent.ACTION_CANCEL: {
	                        ImageView view = (ImageView) v;
	                        view.getDrawable().clearColorFilter();
	                        view.invalidate();
	                        break;
	                    }
	                }
	                return false;
	            }
	        });
			joinBtn.setOnClickListener(this);
			
			SharedPreferences prefs = getActivity().getSharedPreferences("Save", getActivity().MODE_PRIVATE);
			if (prefs.getString("eMail", "") != null && !prefs.getString("eMail", "").equals("") && 
					prefs.getString("pw", "") != null && !prefs.getString("pw", "").equals("")) {
				eMail.setText(prefs.getString("eMail", ""));
				password.setText(prefs.getString("pw", ""));
			}
			if (prefs.getBoolean("auto", false)) {
				autoLogin.setChecked(true);
				regId = GCMRegistrar.getRegistrationId(getActivity());
				url = getResources().getString(R.string.server_url) + "/glowmee/loginRegisterXml.do?";
				url += "eMail=" + eMail.getText().toString().trim() + "&password=" + password.getText().toString().trim() + "&regId=" + regId;
				(new LoginWorker()).execute();
			}
		}
		listMore.addHeaderView(llHeader);
		
		ArrayList<String> list = new ArrayList<String>();
		
		adapter = new DataAdapter(getActivity(), list);
		
		list.add("설정");
		list.add("공지사항");
		list.add("글로우픽 페이스북");
		list.add("광고/제휴 문의");
		
		listMore.setAdapter(adapter);
		listMore.setOnItemClickListener(this);
		
		(new EtcInfoWorker()).execute();
		
		return nowView;
	}
	
	public class EtcInfoWorker extends AsyncTask<Object, Object, Object> {
		@Override
		protected void onPreExecute() {
			CDialog.showLoading(getActivity());
		}
		
		@Override
		protected Object doInBackground(Object... params) {
			Object result = null;
			
			// 접속할 주소 정의
			String url = getResources().getString(R.string.server_url) + "/glowmee/etcInfoXml.do";
			
			// XML 파서 생성
			XmlPullParser parser = XmlParser.getInstance().getParser(url);
			
			// 통신 실패시 예외처리
			if (parser == null) {
				this.cancel(true);
				return null;
			}
			
			try {
				String tag = null;
				int type = parser.getEventType();

				// 파싱 처리를 위한 반복 시작
				while (type != XmlPullParser.END_DOCUMENT) {
					// 읽은 태그의 이름
					tag = parser.getName();

					// 현재 읽고 있는 태그의 종류별로 분기
					switch (type) {
					case XmlPullParser.START_TAG:
						/** 원하는 종류의 시작태그를 만났을 때, 값을 추출 */
						if (tag.equals("facebook")) {
							parser.next();
							facebook = parser.getText();
						} else if (tag.equals("partner")) {
							parser.next();
							partner = parser.getText();
						} else if (tag.equals("android")) {
							parser.next();
							version = parser.getText();
						}
						
						break;

					case XmlPullParser.END_TAG:
						if (tag.equals("item")) {
							
						}
						break;
					}

					// 다음 태그로 이동하고, 상태값을 변경
					type = parser.next();
				}

			} catch (XmlPullParserException e) {
				System.out.println("파서 생성 실패 >> " + e.toString());
			} catch (IOException e) {
				System.out.println("파서 읽기 실패 >> " + e.toString());
			}
			
			return result;
		}

		@Override
		protected void onProgressUpdate(Object... param) {
		}

		@Override
		protected void onPostExecute(Object param) {
			CDialog.hideLoading();
		}
		
		@Override
		protected void onCancelled() {
			CDialog.hideLoading();
			AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), android.R.style.Theme_Holo_Light_Dialog));
			alert.setMessage("일시적인 통신에러입니다.");
			alert.setCancelable(false);
			alert.setPositiveButton("다시 시도", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					(new EtcInfoWorker()).execute();
				}
			});
			alert.setNegativeButton("뒤로 가기", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					getActivity().finish();
				}
			});
			alert.create();
			alert.show();
		}
	}
	
	public class DataAdapter extends ArrayAdapter<String> {
		private LayoutInflater inflater = null;

		// 생성자. 파라미터에 전달되는 List의 제너릭스 선언에 주의한다.
		public DataAdapter(Context context, List<String> objects) {
			super(context, 0, objects);
			inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		// ArrayList에 할당된 각 항목을 하나씩 추출하여 list_item.xml에 표현시키는 메서드
		// 이 메서드는 ListView에 의해서 호출된다.
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			/** 모든 컴포넌트의 최상위 클래스 */
			View view = null;

			// 데이터를 저장할 View 선언. view 객체는 "list_item.xml"파일을 의미한다.
			if (convertView == null) {
				view = inflater.inflate(R.layout.list_more_item, null);
			} else {
				view = convertView;
			}

			// 하나의 데이터 항목을 추출한다.
			String item = getItem(position);
			
			/** "list_item.xml"내의 컨트롤들을 추출하여 데이터 출력. */

			// 추출한 데이터가 존재한다면 "list_item.xml"안의 컨트롤들을 추출하여 처리한다.
			if (item != null) {
				// 이미지를 표시하기 위한 이미지뷰 컨트롤
				TextView moreText = (TextView) view.findViewById(R.id.moreText);
				moreText.setText(item);
			}
			return view;
		}
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.loginBt:
			String eMailText = eMail.getText().toString().trim();
			if (eMailText.equals("")) {
				Toast.makeText(getActivity(), "이메일을 입력하세요.", Toast.LENGTH_SHORT).show();
				return;
			}
			String passwordText = password.getText().toString().trim();
			if (passwordText.equals("")) {
				Toast.makeText(getActivity(), "비밀번호를 입력하세요.", Toast.LENGTH_SHORT).show();
				return;
			}
			
			regId = GCMRegistrar.getRegistrationId(getActivity());
			
			url = getResources().getString(R.string.server_url) + "/glowmee/loginRegisterXml.do?";
	        url += "eMail=" + eMailText + "&password=" + passwordText + "&regId=" + regId;
			
			(new LoginWorker()).execute();
			break;
		case R.id.searchPw:
			Intent intent = new Intent(getActivity(), SearchPw.class);
			startActivity(intent);
			break;
		case R.id.joinBtn:
			Intent joinFirst = new Intent(getActivity(), JoinFirst.class);
			startActivity(joinFirst);
			break;
		case R.id.profileLayoutBt:
			Intent profile = new Intent(getActivity(), ProfileHome.class);
			startActivity(profile);
			break;
		case R.id.editProfileBt:
			Intent edit = new Intent(getActivity(), EditProfile.class);
			startActivityForResult(edit, 1);
			break;
		case R.id.autoLoginText:
			if (UserInfo.getInstance().isAUTO_LOGIN()) {
				autoLogin.setChecked(false);
			} else {
				autoLogin.setChecked(true);
			}
			break;
		}
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {
			if (requestCode == 1) {
				(new ProfileWorker()).execute();
			}
		}
	}
	
	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		switch (buttonView.getId()) {
		case R.id.autoLogin:
			if (isChecked) {
				autoLogin.setChecked(true);
			} else {
				autoLogin.setChecked(false);
			}
			break;
		}
	}
	
	public class LoginWorker extends AsyncTask<Object, AddItem, Object> {
		@Override
		protected void onPreExecute() {
			CDialog.showLoading(getActivity());
		}

		@Override
		protected Object doInBackground(Object... params) {
			Object result = null;
			// XML 파서 생성
			XmlPullParser parser = XmlParser.getInstance().getParser(url);
			// 통신 실패시 예외처리
			if (parser == null) {
				this.cancel(true);
				return null;
			}
			
			try {
				String tag = null;
				int type = parser.getEventType();

				/** 읽은 내용을 담기 위한 변수 */
				String rt = null;
				String rtmsg = null;
				int seq = 0;
				// 파싱 처리를 위한 반복 시작
				while (type != XmlPullParser.END_DOCUMENT) {
					// 읽은 태그의 이름
					tag = parser.getName();

					// 현재 읽고 있는 태그의 종류별로 분기
					switch (type) {
					case XmlPullParser.START_TAG:
						/** 원하는 종류의 시작태그를 만났을 때, 값을 추출 */
						if (tag.equals("rt")) {
							parser.next();
							rt = parser.getText();
						} else if (tag.equals("rtmsg")) {
							parser.next();
							rtmsg = parser.getText();
						} else if (tag.equals("seq")) {
							parser.next();
							seq = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("mail")) {
							parser.next();
							mail = parser.getText();
						} else if (tag.equals("nickName")) {
							parser.next();
							nickName = parser.getText();
						}
						
						break;

					case XmlPullParser.END_TAG:
						
						if (tag.equals("JSPglowmee")) {
							AddItem item = new AddItem(rt, rtmsg, seq);
							publishProgress(item);
						}
						break;
					}

					// 다음 태그로 이동하고, 상태값을 변경
					type = parser.next();
				}

			} catch (XmlPullParserException e) {
				System.out.println("파서 생성 실패 >> " + e.toString());
			} catch (IOException e) {
				System.out.println("파서 읽기 실패 >> " + e.toString());
			}
			
			return result;
		}

		@Override
		protected void onProgressUpdate(AddItem... param) {
			
			if (param[0].getRt().equals("SUCCESS")) {
				UserInfo.getInstance().setUSER_ID(param[0].getSeq());
				UserInfo.getInstance().setUSER_EMAIL(mail.trim());
				UserInfo.getInstance().setUSER_NICKNAME(nickName.trim());
				
				SharedPreferences prefs = getActivity().getSharedPreferences("Save", getActivity().MODE_PRIVATE);      
				SharedPreferences.Editor editor = prefs.edit();
				editor.putString("eMail", eMail.getText().toString().trim()); 
				editor.putString("pw", password.getText().toString().trim());
				
				if (autoLogin.isChecked()) {
					editor.putBoolean("auto", true);
					UserInfo.getInstance().setAUTO_LOGIN(true);
				} else {
					editor.putBoolean("auto", false);
					UserInfo.getInstance().setAUTO_LOGIN(false);
				}
				
				editor.commit();
				
				Fragment newFragment = new More();
				final FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
		        transaction.replace(R.id.main_fragment, newFragment);
		        transaction.commit();
				
			} else {
				AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), android.R.style.Theme_Holo_Light_Dialog));
				alert.setTitle("로그인 실패");
				alert.setMessage(param[0].getRtmsg());
				alert.setCancelable(false);
				alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				});
				alert.create();
				alert.show();
			}
			
		}

		@Override
		protected void onPostExecute(Object param) {
			CDialog.hideLoading();
		}
		
		@Override
		protected void onCancelled() {
			CDialog.hideLoading();
			AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), android.R.style.Theme_Holo_Light_Dialog));
			alert.setMessage("일시적인 통신에러입니다.");
			alert.setCancelable(false);
			alert.setPositiveButton("다시 시도", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					(new LoginWorker()).execute();
				}
			});
			alert.setNegativeButton("뒤로 가기", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					getActivity().finish();
				}
			});
			alert.create();
			alert.show();
		}
	}
	
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		switch (arg2) {
		case 1:
			Intent intent1 = new Intent(getActivity(), Setup.class);
			intent1.putExtra("PARAM_version", version);
			startActivity(intent1);
			break;
		case 2:
			Intent intent2 = new Intent(getActivity(), Notice.class);
			startActivity(intent2);
			break;
		case 3:
			Intent face = new Intent(Intent.ACTION_VIEW, Uri.parse(facebook));
			startActivity(face);
			break;
		case 4:
			Intent site = new Intent(Intent.ACTION_VIEW, Uri.parse(partner));
			startActivity(site);
			break;
		}
	}
	
	public class ProfileWorker extends AsyncTask<Object, RegisterCMD, Object> {
		@Override
		protected void onPreExecute() {
			CDialog.showLoading(getActivity());
		}

		@Override
		protected Object doInBackground(Object... params) {
			Object result = null;
			String url = getResources().getString(R.string.server_url) + "/glowmee/registerXml.do?id=" + UserInfo.getInstance().getUSER_ID();
			
			XmlPullParser parser = XmlParser.getInstance().getParser(url);
			if (parser == null) {
				this.cancel(true);
				return null;
			}
			
			try {
				String tag = null;
				int type = parser.getEventType();

				/** 읽은 내용을 담기 위한 변수 */
				int idRegister = 0;
				String eMail = null;
				String nickName = null;
				int birthYear = 0;
				String skinTypeValue = null;
				String genderValue = null;
				String locationValue1 = null;
				String locationValue2 = null;
				String userTel = null;
				String userAddress = null;
				String thumbnail = null;
				int pouchCount = 0;
				int userPouchCount = 0;
				int reviewCount = 0;
				
				// 파싱 처리를 위한 반복 시작
				while (type != XmlPullParser.END_DOCUMENT) {
					// 읽은 태그의 이름
					tag = parser.getName();

					// 현재 읽고 있는 태그의 종류별로 분기
					switch (type) {
					case XmlPullParser.START_TAG:
						/** 원하는 종류의 시작태그를 만났을 때, 값을 추출 */
						if (tag.equals("idRegister")) {
							parser.next();
							idRegister = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("eMail")) {
							parser.next();
							eMail = parser.getText();
						} else if (tag.equals("nickName")) {
							parser.next();
							nickName = parser.getText();
						} else if (tag.equals("birthYear")) {
							parser.next();
							birthYear = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("skinTypeValue")) {
							parser.next();
							skinTypeValue = parser.getText();
						} else if (tag.equals("genderValue")) {
							parser.next();
							genderValue = parser.getText();
						} else if (tag.equals("locationValue1")) {
							parser.next();
							locationValue1 = parser.getText();
						} else if (tag.equals("locationValue2")) {
							parser.next();
							locationValue2 = parser.getText();
						} else if (tag.equals("userTel")) {
							parser.next();
							userTel = parser.getText();
						} else if (tag.equals("userAddress")) {
							parser.next();
							userAddress = parser.getText();
						} else if (tag.equals("thumbnail")) {
							parser.next();
							thumbnail = parser.getText();
						} else if (tag.equals("pouchCount")) {
							parser.next();
							pouchCount = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("userPouchCount")) {
							parser.next();
							userPouchCount = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("reviewCount")) {
							parser.next();
							reviewCount = Integer.parseInt(parser.getText().trim());
						}
						
						break;

					case XmlPullParser.END_TAG:
						
						if (tag.equals("item")) {
							RegisterCMD item = new RegisterCMD(idRegister, eMail, nickName, locationValue1, locationValue2, birthYear,
									skinTypeValue, genderValue, thumbnail, userTel, userAddress, pouchCount, reviewCount, userPouchCount);
							if (thumbnail != null) {
								try {
									URL url2 = new URL(getResources().getString(R.string.server_url) + item.getCreate_date().trim()); 
									URLConnection conn = url2.openConnection(); 
									conn.connect(); 
									BufferedInputStream bis = new BufferedInputStream(conn.getInputStream()); 
									bm = BitmapFactory.decodeStream(bis); 
									bis.close();
									isImage = true;
								} catch (IOException e) {
									e.printStackTrace();
								}
							}
							
							publishProgress(item);
						}
						break;
					}

					// 다음 태그로 이동하고, 상태값을 변경
					type = parser.next();
				}

			} catch (XmlPullParserException e) {
				System.out.println("파서 생성 실패 >> " + e.toString());
			} catch (IOException e) {
				System.out.println("파서 읽기 실패 >> " + e.toString());
			}
			
			return result;
		}

		@Override
		protected void onProgressUpdate(RegisterCMD... param) {
			userNickName.setText(param[0].getNickName());
			userNickName.setTextSize(22);
			if (param[0].getSkinTypeValue().equals("null") && param[0].getBirthYear() != 0) {
				int age = Calendar.getInstance().get(Calendar.YEAR) - param[0].getBirthYear() + 1;
				userInfo.setText(age + "세");
			} else if (!param[0].getSkinTypeValue().equals("null") && param[0].getBirthYear() == 0) {
				userInfo.setText(param[0].getSkinTypeValue() + "피부");
			} else if (!param[0].getSkinTypeValue().equals("null") && param[0].getBirthYear() != 0) {
				int age = Calendar.getInstance().get(Calendar.YEAR) - param[0].getBirthYear() + 1;
				userInfo.setText(age + "세 " + param[0].getSkinTypeValue() + "피부");
			}
			if (isImage) {
				backUserImg.setImageBitmap(fastblur(bm, 10));
				frontUserImg.setImageBitmap(bm);
			} else {
				backUserImg.setImageDrawable(null);
			}
			
			picksCount.setText(String.valueOf(param[0].getPouchCount()));
			likesCount.setText(String.valueOf(param[0].getUserPouchCount()));
			reviewsCount.setText(String.valueOf(param[0].getReviewCount()));
		}

		@Override
		protected void onPostExecute(Object param) {
			CDialog.hideLoading();
		}
		
		@Override
		protected void onCancelled() {
			CDialog.hideLoading();
			AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), android.R.style.Theme_Holo_Light_Dialog));
			alert.setMessage("일시적인 통신에러입니다.");
			alert.setCancelable(false);
			alert.setPositiveButton("다시 시도", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					(new ProfileWorker()).execute();
				}
			});
			alert.setNegativeButton("뒤로 가기", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					getActivity().finish();
				}
			});
			alert.create();
			alert.show();
		}
	}
	
	public Bitmap fastblur(Bitmap sentBitmap, int radius) {

        // Stack Blur v1.0 from
        // http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html
        //
        // Java Author: Mario Klingemann <mario at quasimondo.com>
        // http://incubator.quasimondo.com
        // created Feburary 29, 2004
        // Android port : Yahel Bouaziz <yahel at kayenko.com>
        // http://www.kayenko.com
        // ported april 5th, 2012

        // This is a compromise between Gaussian Blur and Box blur
        // It creates much better looking blurs than Box Blur, but is
        // 7x faster than my Gaussian Blur implementation.
        //
        // I called it Stack Blur because this describes best how this
        // filter works internally: it creates a kind of moving stack
        // of colors whilst scanning through the image. Thereby it
        // just has to add one new block of color to the right side
        // of the stack and remove the leftmost color. The remaining
        // colors on the topmost layer of the stack are either added on
        // or reduced by one, depending on if they are on the right or
        // on the left side of the stack.
        //
        // If you are using this algorithm in your code please add
        // the following line:
        //
        // Stack Blur Algorithm by Mario Klingemann <mario@quasimondo.com>

        Bitmap bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);

        if (radius < 1) {
            return (null);
        }

        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        int[] pix = new int[w * h];
        bitmap.getPixels(pix, 0, w, 0, 0, w, h);

        int wm = w - 1;
        int hm = h - 1;
        int wh = w * h;
        int div = radius + radius + 1;

        int r[] = new int[wh];
        int g[] = new int[wh];
        int b[] = new int[wh];
        int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
        int vmin[] = new int[Math.max(w, h)];

        int divsum = (div + 1) >> 1;
        divsum *= divsum;
        int dv[] = new int[256 * divsum];
        for (i = 0; i < 256 * divsum; i++) {
            dv[i] = (i / divsum);
        }

        yw = yi = 0;

        int[][] stack = new int[div][3];
        int stackpointer;
        int stackstart;
        int[] sir;
        int rbs;
        int r1 = radius + 1;
        int routsum, goutsum, boutsum;
        int rinsum, ginsum, binsum;

        for (y = 0; y < h; y++) {
            rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
            for (i = -radius; i <= radius; i++) {
                p = pix[yi + Math.min(wm, Math.max(i, 0))];
                sir = stack[i + radius];
                sir[0] = (p & 0xff0000) >> 16;
                sir[1] = (p & 0x00ff00) >> 8;
                sir[2] = (p & 0x0000ff);
                rbs = r1 - Math.abs(i);
                rsum += sir[0] * rbs;
                gsum += sir[1] * rbs;
                bsum += sir[2] * rbs;
                if (i > 0) {
                    rinsum += sir[0];
                    ginsum += sir[1];
                    binsum += sir[2];
                } else {
                    routsum += sir[0];
                    goutsum += sir[1];
                    boutsum += sir[2];
                }
            }
            stackpointer = radius;

            for (x = 0; x < w; x++) {

                r[yi] = dv[rsum];
                g[yi] = dv[gsum];
                b[yi] = dv[bsum];

                rsum -= routsum;
                gsum -= goutsum;
                bsum -= boutsum;

                stackstart = stackpointer - radius + div;
                sir = stack[stackstart % div];

                routsum -= sir[0];
                goutsum -= sir[1];
                boutsum -= sir[2];

                if (y == 0) {
                    vmin[x] = Math.min(x + radius + 1, wm);
                }
                p = pix[yw + vmin[x]];

                sir[0] = (p & 0xff0000) >> 16;
                sir[1] = (p & 0x00ff00) >> 8;
                sir[2] = (p & 0x0000ff);

                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];

                rsum += rinsum;
                gsum += ginsum;
                bsum += binsum;

                stackpointer = (stackpointer + 1) % div;
                sir = stack[(stackpointer) % div];

                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];

                rinsum -= sir[0];
                ginsum -= sir[1];
                binsum -= sir[2];

                yi++;
            }
            yw += w;
        }
        for (x = 0; x < w; x++) {
            rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
            yp = -radius * w;
            for (i = -radius; i <= radius; i++) {
                yi = Math.max(0, yp) + x;

                sir = stack[i + radius];

                sir[0] = r[yi];
                sir[1] = g[yi];
                sir[2] = b[yi];

                rbs = r1 - Math.abs(i);

                rsum += r[yi] * rbs;
                gsum += g[yi] * rbs;
                bsum += b[yi] * rbs;

                if (i > 0) {
                    rinsum += sir[0];
                    ginsum += sir[1];
                    binsum += sir[2];
                } else {
                    routsum += sir[0];
                    goutsum += sir[1];
                    boutsum += sir[2];
                }

                if (i < hm) {
                    yp += w;
                }
            }
            yi = x;
            stackpointer = radius;
            for (y = 0; y < h; y++) {
                // Preserve alpha channel: ( 0xff000000 & pix[yi] )
                pix[yi] = ( 0xff000000 & pix[yi] ) | ( dv[rsum] << 16 ) | ( dv[gsum] << 8 ) | dv[bsum];

                rsum -= routsum;
                gsum -= goutsum;
                bsum -= boutsum;

                stackstart = stackpointer - radius + div;
                sir = stack[stackstart % div];

                routsum -= sir[0];
                goutsum -= sir[1];
                boutsum -= sir[2];

                if (x == 0) {
                    vmin[y] = Math.min(y + r1, hm) * w;
                }
                p = x + vmin[y];

                sir[0] = r[p];
                sir[1] = g[p];
                sir[2] = b[p];

                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];

                rsum += rinsum;
                gsum += ginsum;
                bsum += binsum;

                stackpointer = (stackpointer + 1) % div;
                sir = stack[stackpointer];

                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];

                rinsum -= sir[0];
                ginsum -= sir[1];
                binsum -= sir[2];

                yi += w;
            }
        }
        bitmap.setPixels(pix, 0, w, 0, 0, w, h);

        return (bitmap);
	}

}
